<!DOCTYPE html><html lang="en" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>【深度学习】实例第三部分：TensorFlow | Yang's Harbor</title><meta name="keywords" content="学习,记录,Python,笔记,深度学习"><meta name="author" content="✨YangSier✨,hobart.yang@qq.com"><meta name="copyright" content="✨YangSier✨"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><meta name="description" content="注意：此代码全部为TensorFlow1版本。 查看Tensorflow版本1234567891011from __future__ import absolute_import, division, print_function, unicode_literals# 导入TensorFlow和tf.kerasimport tensorflow as tffrom tensorflow impor">
<meta property="og:type" content="article">
<meta property="og:title" content="【深度学习】实例第三部分：TensorFlow">
<meta property="og:url" content="https://discover304.top/2021/12/01/2021q4/108-2-dl-ex/index.html">
<meta property="og:site_name" content="Yang&#39;s Harbor">
<meta property="og:description" content="注意：此代码全部为TensorFlow1版本。 查看Tensorflow版本1234567891011from __future__ import absolute_import, division, print_function, unicode_literals# 导入TensorFlow和tf.kerasimport tensorflow as tffrom tensorflow impor">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://image.discover304.top/ai/dl/space_work.jpg?imageView2/2/h/300">
<meta property="article:published_time" content="2021-12-01T02:16:42.000Z">
<meta property="article:modified_time" content="2021-12-25T06:48:18.000Z">
<meta property="article:author" content="✨YangSier✨">
<meta property="article:tag" content="学习">
<meta property="article:tag" content="记录">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="笔记">
<meta property="article:tag" content="深度学习">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://image.discover304.top/ai/dl/space_work.jpg?imageView2/2/h/300"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://discover304.top/2021/12/01/2021q4/108-2-dl-ex/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="preconnect" href="//zz.bdstatic.com"/><meta name="google-site-verification" content="ilqpfk3vkgzDNNikz_V37-DOvRyi5wv4Hoi_eyBqvTg"/><meta name="msvalidate.01" content="49D9A50CCF9744E17274791468EDB517"/><meta name="baidu-site-verification" content="code-V24KosyVh1"/><meta name="360-site-verification" content="bd8859c3d74dfa3e8aeee9db30c94bd2"/><meta name="yandex-verification" content="f28ec9bbd50c56f5"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?8030f6052f2fed6a4704d96619f090d6";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><link rel="stylesheet" href="/css/font.css" media="print" onload="this.media='all'"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"We didn't find any results for the search: ${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: 'days',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: {"limitCount":200,"languages":{"author":"Author: ✨YangSier✨","link":"Link: ","source":"Source: Yang's Harbor","info":"Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source."}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"Traditional Chinese Activated Manually","cht_to_chs":"Simplified Chinese Activated Manually","day_to_night":"Dark Mode Activated Manually","night_to_day":"Light Mode Activated Manually","bgLight":"#ffc910","bgDark":"#02c3f6","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: true
};

var saveToLocal = {
  set: function setWithExpiry(key, value, ttl) {
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}

// https://stackoverflow.com/questions/16839698/jquery-getscript-alternative-in-native-javascript
const getScript = url => new Promise((resolve, reject) => {
  const script = document.createElement('script')
  script.src = url
  script.async = true
  script.onerror = reject
  script.onload = script.onreadystatechange = function() {
    const loadState = this.readyState
    if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
    script.onload = script.onreadystatechange = null
    resolve()
  }
  document.head.appendChild(script)
})</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-12-25 14:48:18'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = 'false'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }const asideStatus = saveToLocal.get('aside-status')
if (asideStatus !== undefined) {
   if (asideStatus === 'hide') {
     document.documentElement.classList.add('hide-aside')
   } else {
     document.documentElement.classList.remove('hide-aside')
   }
}})()</script><meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="Yang's Harbor" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">Loading...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="/img/head.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">243</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">88</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">Categories</div><div class="length-num">23</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Links</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Articles</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archive</span></a></li><li><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Category</span></a></li><li><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></li></ul></div></div></div></div><div id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(https://image.discover304.top/ai/dl/space_work.jpg?imageView2/2/h/300)"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Yang's Harbor</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Links</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> About</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Articles</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archive</span></a></li><li><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Category</span></a></li><li><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">【深度学习】实例第三部分：TensorFlow</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2021-12-01T02:16:42.000Z" title="Created 2021-12-01 10:16:42">2021-12-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2021-12-25T06:48:18.000Z" title="Updated 2021-12-25 14:48:18">2021-12-25</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/NoteBook/">NoteBook</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/NoteBook/PythonNote/">PythonNote</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">Word count:</span><span class="word-count">4.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">Reading time:</span><span>20min</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>注意：此代码全部为TensorFlow1版本。</p>
<h2 id="查看Tensorflow版本"><a href="#查看Tensorflow版本" class="headerlink" title="查看Tensorflow版本"></a>查看Tensorflow版本</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> absolute_import, division, print_function, unicode_literals</span><br><span class="line"></span><br><span class="line"><span class="comment"># 导入TensorFlow和tf.keras</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">from</span> tensorflow <span class="keyword">import</span> keras</span><br><span class="line"></span><br><span class="line"><span class="comment"># 导入辅助库</span></span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(tf.__version__)</span><br></pre></td></tr></table></figure>

<h2 id="Helloworld程序"><a href="#Helloworld程序" class="headerlink" title="Helloworld程序"></a>Helloworld程序</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># tf的helloworld程序</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"></span><br><span class="line">hello = tf.constant(<span class="string">&#x27;Hello, world!&#x27;</span>)  <span class="comment"># 定义一个常量</span></span><br><span class="line">sess = tf.Session()  <span class="comment"># 创建一个session</span></span><br><span class="line"><span class="built_in">print</span>(sess.run(hello))  <span class="comment"># 计算</span></span><br><span class="line">sess.close()</span><br></pre></td></tr></table></figure>

<h2 id="张量相加"><a href="#张量相加" class="headerlink" title="张量相加"></a>张量相加</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 常量加法运算示例</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line">os.environ[<span class="string">&#x27;TF_CPP_MIN_LOG_LEVEL&#x27;</span>] = <span class="string">&#x27;2&#x27;</span>  <span class="comment"># 调整警告级别</span></span><br><span class="line"></span><br><span class="line">a = tf.constant(<span class="number">5.0</span>)  <span class="comment"># 定义常量a</span></span><br><span class="line">b = tf.constant(<span class="number">1.0</span>)  <span class="comment"># 定义常量a</span></span><br><span class="line">c = tf.add(a, b)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;c:&quot;</span>, c)</span><br><span class="line"></span><br><span class="line">graph = tf.get_default_graph()  <span class="comment"># 获取缺省图</span></span><br><span class="line"><span class="built_in">print</span>(graph)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    <span class="built_in">print</span>(sess.run(c))  <span class="comment"># 执行计算</span></span><br></pre></td></tr></table></figure>

<h2 id="查看图对象"><a href="#查看图对象" class="headerlink" title="查看图对象"></a>查看图对象</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 常量加法运算示例</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line">os.environ[<span class="string">&#x27;TF_CPP_MIN_LOG_LEVEL&#x27;</span>] = <span class="string">&#x27;2&#x27;</span>  <span class="comment"># 调整警告级别</span></span><br><span class="line"></span><br><span class="line">a = tf.constant(<span class="number">5.0</span>)  <span class="comment"># 定义常量a</span></span><br><span class="line">b = tf.constant(<span class="number">1.0</span>)  <span class="comment"># 定义常量a</span></span><br><span class="line">c = tf.add(a, b)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;c:&quot;</span>, c)</span><br><span class="line"></span><br><span class="line">graph = tf.get_default_graph()  <span class="comment"># 获取缺省图</span></span><br><span class="line"><span class="built_in">print</span>(graph)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    <span class="built_in">print</span>(sess.run(c))  <span class="comment"># 执行计算</span></span><br><span class="line">    <span class="built_in">print</span>(a.graph)  <span class="comment"># 通过tensor获取graph对象</span></span><br><span class="line">    <span class="built_in">print</span>(c.graph)  <span class="comment"># 通过op获取graph对象</span></span><br><span class="line">    <span class="built_in">print</span>(sess.graph)  <span class="comment"># 通过session获取graph对象</span></span><br></pre></td></tr></table></figure>

<h2 id="指定执行某个图"><a href="#指定执行某个图" class="headerlink" title="指定执行某个图"></a>指定执行某个图</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 创建多个图，指定图运行</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line">os.environ[<span class="string">&#x27;TF_CPP_MIN_LOG_LEVEL&#x27;</span>] = <span class="string">&#x27;2&#x27;</span>  <span class="comment"># 调整警告级别</span></span><br><span class="line"></span><br><span class="line">a = tf.constant(<span class="number">5.0</span>)  <span class="comment"># 定义常量a</span></span><br><span class="line">b = tf.constant(<span class="number">1.0</span>)  <span class="comment"># 定义常量b</span></span><br><span class="line">c = tf.add(a, b)</span><br><span class="line"></span><br><span class="line">graph = tf.get_default_graph()  <span class="comment"># 获取缺省图</span></span><br><span class="line"><span class="built_in">print</span>(graph)</span><br><span class="line"></span><br><span class="line">graph2 = tf.Graph()</span><br><span class="line"><span class="built_in">print</span>(graph2)</span><br><span class="line"><span class="keyword">with</span> graph2.as_default(): <span class="comment"># 在指定图上创建op</span></span><br><span class="line">    d = tf.constant(<span class="number">11.0</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> tf.Session(graph=graph2) <span class="keyword">as</span> sess:</span><br><span class="line">    <span class="built_in">print</span>(sess.run(d))  <span class="comment"># 执行计算</span></span><br><span class="line">    <span class="comment"># print(sess.run(c))  # 报错</span></span><br></pre></td></tr></table></figure>

<h2 id="查看张量属性"><a href="#查看张量属性" class="headerlink" title="查看张量属性"></a>查看张量属性</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 创建多个图，指定图运行</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line">os.environ[<span class="string">&#x27;TF_CPP_MIN_LOG_LEVEL&#x27;</span>] = <span class="string">&#x27;2&#x27;</span>  <span class="comment"># 调整警告级别</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># a = tf.constant(5.0)  # 定义常量a</span></span><br><span class="line"><span class="comment"># a = tf.constant([1,2,3])</span></span><br><span class="line">a = tf.constant([[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>],[<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]])</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    <span class="built_in">print</span>(sess.run(a))  <span class="comment"># 执行计算</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;name:&quot;</span>, a.name)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;dtype:&quot;</span>, a.dtype)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;shape:&quot;</span>, a.shape)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;op:&quot;</span>, a.op)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;graph:&quot;</span>, a.graph)</span><br></pre></td></tr></table></figure>

<h2 id="生成张量"><a href="#生成张量" class="headerlink" title="生成张量"></a>生成张量</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 创建张量操作</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"></span><br><span class="line"><span class="comment"># 生成值全为0的张量</span></span><br><span class="line">tensor_zeros = tf.zeros(shape=[<span class="number">2</span>, <span class="number">3</span>], dtype=<span class="string">&quot;float32&quot;</span>)</span><br><span class="line"><span class="comment"># 生成值全为1的张量</span></span><br><span class="line">tensor_ones = tf.ones(shape=[<span class="number">2</span>, <span class="number">3</span>], dtype=<span class="string">&quot;float32&quot;</span>)</span><br><span class="line"><span class="comment"># 创建正态分布张量</span></span><br><span class="line">tensor_nd = tf.random_normal(shape=[<span class="number">10</span>],</span><br><span class="line">                             mean=<span class="number">1.7</span>,</span><br><span class="line">                             stddev=<span class="number">0.2</span>,</span><br><span class="line">                             dtype=<span class="string">&quot;float32&quot;</span>)</span><br><span class="line"><span class="comment"># 生成和输入张量形状一样的张量，值全为1</span></span><br><span class="line">tensor_zeros_like = tf.zeros_like(tensor_ones)</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    <span class="built_in">print</span>(tensor_zeros.<span class="built_in">eval</span>())  <span class="comment"># eval表示在session中计算该张量</span></span><br><span class="line">    <span class="built_in">print</span>(tensor_ones.<span class="built_in">eval</span>())</span><br><span class="line">    <span class="built_in">print</span>(tensor_nd.<span class="built_in">eval</span>())</span><br><span class="line">    <span class="built_in">print</span>(tensor_zeros_like.<span class="built_in">eval</span>())</span><br></pre></td></tr></table></figure>

<h2 id="张量类型转换"><a href="#张量类型转换" class="headerlink" title="张量类型转换"></a>张量类型转换</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 张量类型转换</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"></span><br><span class="line">tensor_ones = tf.ones(shape=[<span class="number">2</span>, <span class="number">3</span>], dtype=<span class="string">&quot;int32&quot;</span>)</span><br><span class="line">tensor_float = tf.constant([<span class="number">1.1</span>, <span class="number">2.2</span>, <span class="number">3.3</span>])</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    <span class="built_in">print</span>(tf.cast(tensor_ones, tf.float32).<span class="built_in">eval</span>())</span><br><span class="line">    <span class="comment"># print(tf.cast(tensor_float, tf.string).eval()) #不支持浮点数到字符串直接转换</span></span><br></pre></td></tr></table></figure>

<h2 id="占位符使用"><a href="#占位符使用" class="headerlink" title="占位符使用"></a>占位符使用</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 占位符示例</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"></span><br><span class="line"><span class="comment"># 不确定数据，先使用占位符占个位置</span></span><br><span class="line">plhd = tf.placeholder(tf.float32, [<span class="number">2</span>, <span class="number">3</span>])  <span class="comment"># 2行3列的tensor</span></span><br><span class="line">plhd2 = tf.placeholder(tf.float32, [<span class="literal">None</span>, <span class="number">3</span>])  <span class="comment"># N行3列的tensor</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    d = [[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>],</span><br><span class="line">         [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]]</span><br><span class="line">    <span class="built_in">print</span>(sess.run(plhd, feed_dict=&#123;plhd: d&#125;))</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;shape:&quot;</span>, plhd.shape)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;name:&quot;</span>, plhd.name)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;graph:&quot;</span>, plhd.graph)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;op:&quot;</span>, plhd.op)</span><br><span class="line">    <span class="built_in">print</span>(sess.run(plhd2, feed_dict=&#123;plhd2: d&#125;))</span><br></pre></td></tr></table></figure>

<h2 id="改变张量形状"><a href="#改变张量形状" class="headerlink" title="改变张量形状"></a>改变张量形状</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 改变张量形状示例(重点)</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"></span><br><span class="line">pld = tf.placeholder(tf.float32, [<span class="literal">None</span>, <span class="number">3</span>])</span><br><span class="line"><span class="built_in">print</span>(pld)</span><br><span class="line"></span><br><span class="line">pld.set_shape([<span class="number">4</span>, <span class="number">3</span>])</span><br><span class="line"><span class="built_in">print</span>(pld)</span><br><span class="line"><span class="comment"># pld.set_shape([3, 3]) #报错，静态形状一旦固定就不能再设置静态形状</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 动态形状可以创建一个新的张量，改变时候一定要注意元素的数量要匹配</span></span><br><span class="line">new_pld = tf.reshape(pld, [<span class="number">3</span>, <span class="number">4</span>])</span><br><span class="line"><span class="built_in">print</span>(new_pld)</span><br><span class="line"><span class="comment"># new_pld = tf.reshape(pld, [2, 4]) # 报错，元素的数量不匹配</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>

<h2 id="数学计算"><a href="#数学计算" class="headerlink" title="数学计算"></a>数学计算</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 数学计算示例</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"></span><br><span class="line">x = tf.constant([[<span class="number">1</span>, <span class="number">2</span>], [<span class="number">3</span>, <span class="number">4</span>]], dtype=tf.float32)</span><br><span class="line">y = tf.constant([[<span class="number">4</span>, <span class="number">3</span>], [<span class="number">3</span>, <span class="number">2</span>]], dtype=tf.float32)</span><br><span class="line"></span><br><span class="line">x_add_y = tf.add(x, y)  <span class="comment"># 张量相加</span></span><br><span class="line">x_mul_y = tf.matmul(x, y)  <span class="comment"># 张量相乘</span></span><br><span class="line">log_x = tf.log(x)  <span class="comment"># log(x)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># reduce_sum: 此函数计算一个张量的各个维度上元素的总和</span></span><br><span class="line">x_sum_1 = tf.reduce_sum(x, axis=[<span class="number">1</span>]) <span class="comment">#0-列方向 1-行方向</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># segment_sum: 沿张量的片段计算总和</span></span><br><span class="line"><span class="comment"># 函数返回的是一个Tensor,它与data有相同的类型,与data具有相同的形状</span></span><br><span class="line"><span class="comment"># 但大小为 k(段的数目)的维度0除外</span></span><br><span class="line">data = tf.constant([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>], dtype=tf.float32)</span><br><span class="line">segment_ids = tf.constant([<span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>], dtype=tf.int32)</span><br><span class="line">x_seg_sum = tf.segment_sum(data, segment_ids)  <span class="comment"># [6, 9, 40]</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    <span class="built_in">print</span>(x_add_y.<span class="built_in">eval</span>())</span><br><span class="line">    <span class="built_in">print</span>(x_mul_y.<span class="built_in">eval</span>())</span><br><span class="line">    <span class="built_in">print</span>(log_x.<span class="built_in">eval</span>())</span><br><span class="line">    <span class="built_in">print</span>(x_sum_1.<span class="built_in">eval</span>())</span><br><span class="line">    <span class="built_in">print</span>(x_seg_sum.<span class="built_in">eval</span>())</span><br></pre></td></tr></table></figure>



<h2 id="变量使用示例"><a href="#变量使用示例" class="headerlink" title="变量使用示例"></a>变量使用示例</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 变量OP示例</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="comment"># 创建普通张量</span></span><br><span class="line">a = tf.constant([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>])</span><br><span class="line"><span class="comment"># 创建变量</span></span><br><span class="line">var = tf.Variable(tf.random_normal([<span class="number">2</span>, <span class="number">3</span>], mean=<span class="number">0.0</span>, stddev=<span class="number">1.0</span>),</span><br><span class="line">                  name=<span class="string">&quot;variable&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 变量必须显式初始化, 这里定义的是初始化操作，并没有运行</span></span><br><span class="line">init_op = tf.global_variables_initializer()</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    sess.run(init_op)</span><br><span class="line">    <span class="built_in">print</span>(sess.run([a, var]))</span><br></pre></td></tr></table></figure>

<h2 id="可视化"><a href="#可视化" class="headerlink" title="可视化"></a>可视化</h2><p>第一步：编写代码</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 变量OP示例</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27; 变量OP</span></span><br><span class="line"><span class="string">1. 变量OP能够持久化保存，普通张量则不可</span></span><br><span class="line"><span class="string">2. 当定义一个变量OP时，在会话中进行初始化</span></span><br><span class="line"><span class="string">3. name参数：在tensorboard使用的时候显示名字，可以让相同的OP进行区分</span></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建普通张量</span></span><br><span class="line">a = tf.constant([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>])</span><br><span class="line"><span class="comment"># 创建变量</span></span><br><span class="line">var = tf.Variable(tf.random_normal([<span class="number">2</span>, <span class="number">3</span>], mean=<span class="number">0.0</span>, stddev=<span class="number">1.0</span>),</span><br><span class="line">                  name=<span class="string">&quot;variable&quot;</span>)</span><br><span class="line"></span><br><span class="line">b = tf.constant(<span class="number">3.0</span>, name=<span class="string">&quot;a&quot;</span>)</span><br><span class="line">c = tf.constant(<span class="number">4.0</span>, name=<span class="string">&quot;b&quot;</span>)</span><br><span class="line">d = tf.add(b, c, name=<span class="string">&quot;add&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 变量必须显式初始化, 这里定义的是初始化操作，并没有运行</span></span><br><span class="line">init_op = tf.global_variables_initializer()</span><br><span class="line"></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    sess.run(init_op)</span><br><span class="line">    <span class="comment"># 将程序图结构写入事件文件</span></span><br><span class="line">    fw = tf.summary.FileWriter(<span class="string">&quot;../summary/&quot;</span>, graph=sess.graph)</span><br><span class="line">    <span class="built_in">print</span>(sess.run([a, var]))</span><br></pre></td></tr></table></figure>

<p>第二步：启动tensorborad</p>
<figure class="highlight abnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tensorboard  --logdir<span class="operator">=</span><span class="string">&quot;PycharmProjects/tensorflow_study/summary/&quot;</span></span><br></pre></td></tr></table></figure>

<p>第三步：访问tensorborad主页</p>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http:<span class="regexp">//</span><span class="number">127.0</span>.<span class="number">0.1</span>:<span class="number">6006</span></span><br></pre></td></tr></table></figure>

<h2 id="实现线性回归"><a href="#实现线性回归" class="headerlink" title="实现线性回归"></a>实现线性回归</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 线性回归示例</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"></span><br><span class="line"><span class="comment"># 第一步：创建数据</span></span><br><span class="line">x = tf.random_normal([<span class="number">100</span>, <span class="number">1</span>], mean=<span class="number">1.75</span>, stddev=<span class="number">0.5</span>, name=<span class="string">&quot;x_data&quot;</span>)</span><br><span class="line">y_true = tf.matmul(x, [[<span class="number">2.0</span>]]) + <span class="number">5.0</span>  <span class="comment"># 矩阵相乘必须是二维的</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 第二步：建立线性回归模型</span></span><br><span class="line"><span class="comment"># 建立模型时，随机建立权重、偏置 y = wx + b</span></span><br><span class="line"><span class="comment"># 权重需要不断更新，所以必须是变量类型. trainable指定该变量是否能随梯度下降一起变化</span></span><br><span class="line">weight = tf.Variable(tf.random_normal([<span class="number">1</span>, <span class="number">1</span>], name=<span class="string">&quot;w&quot;</span>),</span><br><span class="line">                     trainable=<span class="literal">True</span>)  <span class="comment"># 训练过程中值是否允许变化</span></span><br><span class="line">bias = tf.Variable(<span class="number">0.0</span>, name=<span class="string">&quot;b&quot;</span>, trainable=<span class="literal">True</span>)  <span class="comment"># 偏置</span></span><br><span class="line">y_predict = tf.matmul(x, weight) + bias  <span class="comment"># 计算 wx + b</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># # 第三步：求损失函数，误差(均方差)</span></span><br><span class="line">loss = tf.reduce_mean(tf.square(y_true - y_predict))</span><br><span class="line"></span><br><span class="line"><span class="comment"># # 第四步：使用梯度下降法优化损失</span></span><br><span class="line"><span class="comment"># 学习率是比价敏感的参数，过小会导致收敛慢，过大可能导致梯度爆炸</span></span><br><span class="line">train_op = tf.train.GradientDescentOptimizer(<span class="number">0.1</span>).minimize(loss)</span><br><span class="line"></span><br><span class="line"><span class="comment">### 收集损失值</span></span><br><span class="line">tf.summary.scalar(<span class="string">&quot;losses&quot;</span>, loss)</span><br><span class="line">merged = tf.summary.merge_all() <span class="comment">#将所有的摘要信息保存到磁盘</span></span><br><span class="line"></span><br><span class="line">init_op = tf.global_variables_initializer()</span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:  <span class="comment"># 通过Session运行op</span></span><br><span class="line">    sess.run(init_op)</span><br><span class="line">    <span class="comment"># 打印初始权重、偏移值</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;weight:&quot;</span>, weight.<span class="built_in">eval</span>(), <span class="string">&quot; bias:&quot;</span>, bias.<span class="built_in">eval</span>())</span><br><span class="line"></span><br><span class="line">    <span class="comment">### 指定事件文件</span></span><br><span class="line">    fw = tf.summary.FileWriter(<span class="string">&quot;../summary/&quot;</span>, graph=sess.graph)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">500</span>):  <span class="comment"># 循环执行训练</span></span><br><span class="line">        sess.run(train_op)  <span class="comment"># 执行训练</span></span><br><span class="line">        summary = sess.run(merged) <span class="comment">### 运行合并摘要op</span></span><br><span class="line">        fw.add_summary(summary, i) <span class="comment">### 写入文件</span></span><br><span class="line">        <span class="built_in">print</span>(i, <span class="string">&quot;:&quot;</span>, i, <span class="string">&quot;weight:&quot;</span>, weight.<span class="built_in">eval</span>(), <span class="string">&quot; bias:&quot;</span>, bias.<span class="built_in">eval</span>())</span><br></pre></td></tr></table></figure>

<h2 id="模型保存与加载"><a href="#模型保存与加载" class="headerlink" title="模型保存与加载"></a>模型保存与加载</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 模型保存示例</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line"><span class="comment"># 第一步：创建数据</span></span><br><span class="line">x = tf.random_normal([<span class="number">100</span>, <span class="number">1</span>], mean=<span class="number">1.75</span>, stddev=<span class="number">0.5</span>, name=<span class="string">&quot;x_data&quot;</span>)</span><br><span class="line">y_true = tf.matmul(x, [[<span class="number">2.0</span>]]) + <span class="number">5.0</span>  <span class="comment"># 矩阵相乘必须是二维的</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 第二步：建立线性回归模型</span></span><br><span class="line"><span class="comment"># 建立模型时，随机建立权重、偏置 y = wx + b</span></span><br><span class="line"><span class="comment"># 权重需要不断更新，所以必须是变量类型. trainable指定该变量是否能随梯度下降一起变化</span></span><br><span class="line">weight = tf.Variable(tf.random_normal([<span class="number">1</span>, <span class="number">1</span>], name=<span class="string">&quot;w&quot;</span>),</span><br><span class="line">                     trainable=<span class="literal">True</span>)  <span class="comment"># 训练过程中值是否允许变化</span></span><br><span class="line">bias = tf.Variable(<span class="number">0.0</span>, name=<span class="string">&quot;b&quot;</span>, trainable=<span class="literal">True</span>)  <span class="comment"># 偏置</span></span><br><span class="line">y_predict = tf.matmul(x, weight) + bias  <span class="comment"># 计算 wx + b</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># # 第三步：求损失函数，误差(均方差)</span></span><br><span class="line">loss = tf.reduce_mean(tf.square(y_true - y_predict))</span><br><span class="line"></span><br><span class="line"><span class="comment"># # 第四步：使用梯度下降法优化损失</span></span><br><span class="line"><span class="comment"># 学习率是比价敏感的参数，过小会导致收敛慢，过大可能导致梯度爆炸</span></span><br><span class="line">train_op = tf.train.GradientDescentOptimizer(<span class="number">0.1</span>).minimize(loss)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 收集损失值</span></span><br><span class="line">tf.summary.scalar(<span class="string">&quot;losses&quot;</span>, loss)</span><br><span class="line">merged = tf.summary.merge_all() <span class="comment">#将所有的摘要信息保存到磁盘</span></span><br><span class="line"></span><br><span class="line">init_op = tf.global_variables_initializer()</span><br><span class="line"></span><br><span class="line">saver = tf.train.Saver() <span class="comment">#实例化Saver</span></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:  <span class="comment"># 通过Session运行op</span></span><br><span class="line">    sess.run(init_op)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;weight:&quot;</span>, weight.<span class="built_in">eval</span>(), <span class="string">&quot; bias:&quot;</span>, bias.<span class="built_in">eval</span>())     <span class="comment"># 打印初始权重、偏移值</span></span><br><span class="line">    fw = tf.summary.FileWriter(<span class="string">&quot;../summary/&quot;</span>, graph=sess.graph) <span class="comment"># 指定事件文件</span></span><br><span class="line">    <span class="comment"># 训练之前，加载之前训练的模型，覆盖之前的参数</span></span><br><span class="line">    <span class="keyword">if</span> os.path.exists(<span class="string">&quot;../model/linear_model/checkpoint&quot;</span>):</span><br><span class="line">        saver.restore(sess, <span class="string">&quot;../model/linear_model/&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">500</span>):  <span class="comment"># 循环执行训练</span></span><br><span class="line">        sess.run(train_op)  <span class="comment"># 执行训练</span></span><br><span class="line">        summary = sess.run(merged) <span class="comment"># 运行合并后的tensor</span></span><br><span class="line">        fw.add_summary(summary, i)</span><br><span class="line">        <span class="built_in">print</span>(i, <span class="string">&quot;:&quot;</span>, i, <span class="string">&quot;weight:&quot;</span>, weight.<span class="built_in">eval</span>(), <span class="string">&quot; bias:&quot;</span>, bias.<span class="built_in">eval</span>())</span><br><span class="line"></span><br><span class="line">    saver.save(sess, <span class="string">&quot;../model/linear_model/&quot;</span>)</span><br></pre></td></tr></table></figure>

<h2 id="CSV样本读取"><a href="#CSV样本读取" class="headerlink" title="CSV样本读取"></a>CSV样本读取</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># csv文件读取示例</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">def</span> <span class="title function_">csv_read</span>(<span class="params">filelist</span>):</span><br><span class="line">    <span class="comment"># 构建文件队列</span></span><br><span class="line">    file_queue = tf.train.string_input_producer(filelist)</span><br><span class="line">    <span class="comment"># 构建csv reader，读取队列内容（一行）</span></span><br><span class="line">    reader = tf.TextLineReader()</span><br><span class="line">    k, v = reader.read(file_queue)</span><br><span class="line">    <span class="comment"># 对每行内容进行解码</span></span><br><span class="line">    <span class="comment">## record_defaults：指定每一个样本每一列的类型，指定默认值</span></span><br><span class="line">    records = [[<span class="string">&quot;None&quot;</span>], [<span class="string">&quot;None&quot;</span>]]</span><br><span class="line">    example, label = tf.decode_csv(v, record_defaults=records)  <span class="comment"># 每行两个值</span></span><br><span class="line">    <span class="comment"># 批处理</span></span><br><span class="line">    <span class="comment"># batch_size: 跟队列大小无关，只决定本批次取多少数据</span></span><br><span class="line">    example_bat, label_bat = tf.train.batch([example, label],</span><br><span class="line">                                            batch_size=<span class="number">9</span>,</span><br><span class="line">                                            num_threads=<span class="number">1</span>,</span><br><span class="line">                                            capacity=<span class="number">9</span>)</span><br><span class="line">    <span class="keyword">return</span> example_bat, label_bat</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    <span class="comment"># 找到文件，构造一个列表</span></span><br><span class="line">    dir_name = <span class="string">&quot;./test_data/&quot;</span></span><br><span class="line">    file_names = os.listdir(dir_name)</span><br><span class="line">    file_list = []</span><br><span class="line">    <span class="keyword">for</span> f <span class="keyword">in</span> file_names:</span><br><span class="line">        file_list.append(os.path.join(dir_name, f))  <span class="comment"># 拼接目录和文件名</span></span><br><span class="line">        </span><br><span class="line">    example, label = csv_read(file_list)</span><br><span class="line">    <span class="comment"># 开启session运行结果</span></span><br><span class="line">    <span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">        coord = tf.train.Coordinator() <span class="comment"># 定义线程协调器</span></span><br><span class="line">        <span class="comment"># 开启读取文件线程</span></span><br><span class="line">        <span class="comment"># 调用 tf.train.start_queue_runners 之后，才会真正把tensor推入内存序列中</span></span><br><span class="line">        <span class="comment"># 供计算单元调用，否则会由于内存序列为空，数据流图会处于一直等待状态</span></span><br><span class="line">        <span class="comment"># 返回一组线程</span></span><br><span class="line">        threads = tf.train.start_queue_runners(sess, coord=coord)</span><br><span class="line">        <span class="built_in">print</span>(sess.run([example, label])) <span class="comment"># 打印读取的内容</span></span><br><span class="line">        <span class="comment"># 回收线程</span></span><br><span class="line">        coord.request_stop()</span><br><span class="line">        coord.join(threads)</span><br></pre></td></tr></table></figure>

<h2 id="图像样本读取"><a href="#图像样本读取" class="headerlink" title="图像样本读取"></a>图像样本读取</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 图片文件读取示例</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">img_read</span>(<span class="params">filelist</span>):</span><br><span class="line">    <span class="comment"># 构建文件队列</span></span><br><span class="line">    file_queue = tf.train.string_input_producer(filelist)</span><br><span class="line">    <span class="comment"># 构建reader读取文件内容，默认读取一张图片</span></span><br><span class="line">    reader = tf.WholeFileReader()</span><br><span class="line">    k, v = reader.read(file_queue)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 对图片数据进行解码</span></span><br><span class="line">    img = tf.image.decode_jpeg(v)  </span><br><span class="line"></span><br><span class="line">    <span class="comment"># 批处理, 图片需要处理成统一大小</span></span><br><span class="line">    img_resized = tf.image.resize(img, [<span class="number">200</span>, <span class="number">200</span>])  <span class="comment"># 200*200</span></span><br><span class="line">    img_resized.set_shape([<span class="number">200</span>, <span class="number">200</span>, <span class="number">3</span>])  <span class="comment"># 固定样本形状，批处理时对数据形状有要求</span></span><br><span class="line">    img_bat = tf.train.batch([img_resized],</span><br><span class="line">                             batch_size=<span class="number">10</span>,</span><br><span class="line">                             num_threads=<span class="number">1</span>)</span><br><span class="line">    <span class="keyword">return</span> img_bat</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    <span class="comment"># 找到文件，构造一个列表</span></span><br><span class="line">    dir_name = <span class="string">&quot;../data/test_img/&quot;</span></span><br><span class="line">    file_names = os.listdir(dir_name)</span><br><span class="line">    file_list = []</span><br><span class="line">    <span class="keyword">for</span> f <span class="keyword">in</span> file_names:</span><br><span class="line">        file_list.append(os.path.join(dir_name, f))  <span class="comment"># 拼接目录和文件名</span></span><br><span class="line">    imgs = img_read(file_list)</span><br><span class="line">    <span class="comment"># 开启session运行结果</span></span><br><span class="line">    <span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">        coord = tf.train.Coordinator()  <span class="comment"># 定义线程协调器</span></span><br><span class="line">        <span class="comment"># 开启读取文件线程</span></span><br><span class="line">        <span class="comment"># 调用 tf.train.start_queue_runners 之后，才会真正把tensor推入内存序列中</span></span><br><span class="line">        <span class="comment"># 供计算单元调用，否则会由于内存序列为空，数据流图会处于一直等待状态</span></span><br><span class="line">        <span class="comment"># 返回一组线程</span></span><br><span class="line">        threads = tf.train.start_queue_runners(sess, coord=coord)</span><br><span class="line">        <span class="comment"># print(sess.run([imgs]))  # 打印读取的内容</span></span><br><span class="line">        imgs = imgs.<span class="built_in">eval</span>()</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 回收线程</span></span><br><span class="line">        coord.request_stop()</span><br><span class="line">        coord.join(threads)</span><br><span class="line"></span><br><span class="line"><span class="comment">## 显示图片</span></span><br><span class="line"><span class="built_in">print</span>(imgs.shape)</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"></span><br><span class="line">plt.figure(<span class="string">&quot;Img Show&quot;</span>, facecolor=<span class="string">&quot;lightgray&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>):</span><br><span class="line">    plt.subplot(<span class="number">2</span>, <span class="number">5</span>, i+<span class="number">1</span>)</span><br><span class="line">    plt.xticks([])</span><br><span class="line">    plt.yticks([])</span><br><span class="line">    plt.imshow(imgs[i].astype(<span class="string">&quot;int32&quot;</span>))</span><br><span class="line"></span><br><span class="line">plt.tight_layout()</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>

<h2 id="实现手写体识别"><a href="#实现手写体识别" class="headerlink" title="实现手写体识别"></a>实现手写体识别</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 手写体识别</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">from</span> tensorflow.examples.tutorials.mnist <span class="keyword">import</span> input_data</span><br><span class="line"><span class="keyword">import</span> pylab</span><br><span class="line"></span><br><span class="line"><span class="comment"># 读入数据集(如果没有则在线下载)，并转换成独热编码</span></span><br><span class="line"><span class="comment"># 如果不能下载，则到http://yann.lecun.com/exdb/mnist/进行手工下载，下载后拷贝到当前MNIST_data目录下</span></span><br><span class="line">mnist = input_data.read_data_sets(<span class="string">&quot;MNIST_data/&quot;</span>, one_hot=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">x = tf.placeholder(tf.float32, [<span class="literal">None</span>, <span class="number">784</span>])  <span class="comment"># 占位符，输入</span></span><br><span class="line">y = tf.placeholder(tf.float32, [<span class="literal">None</span>, <span class="number">10</span>])  <span class="comment"># 占位符，输出</span></span><br><span class="line"></span><br><span class="line">W = tf.Variable(tf.random_normal([<span class="number">784</span>, <span class="number">10</span>]))  <span class="comment"># 权重</span></span><br><span class="line">b = tf.Variable(tf.zeros([<span class="number">10</span>]))  <span class="comment"># 偏置值</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 构建模型</span></span><br><span class="line">pred_y = tf.nn.softmax(tf.matmul(x, W) + b)  <span class="comment"># softmax分类</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;pred_y.shape:&quot;</span>, pred_y.shape)</span><br><span class="line"><span class="comment"># 损失函数</span></span><br><span class="line">cross_entropy = -tf.reduce_sum(y * tf.log(pred_y),</span><br><span class="line">                               reduction_indices=<span class="number">1</span>)  <span class="comment"># 求交叉熵</span></span><br><span class="line">cost = tf.reduce_mean(cross_entropy)  <span class="comment"># 求损失函数平均值</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 参数设置</span></span><br><span class="line">lr = <span class="number">0.01</span></span><br><span class="line"><span class="comment"># 梯度下降优化器</span></span><br><span class="line">optimizer = tf.train.GradientDescentOptimizer(lr).minimize(cost)</span><br><span class="line"></span><br><span class="line">training_epochs = <span class="number">200</span></span><br><span class="line">batch_size = <span class="number">100</span></span><br><span class="line">saver = tf.train.Saver()</span><br><span class="line">model_path = <span class="string">&quot;../model/mnist/mnist_model.ckpt&quot;</span>  <span class="comment"># 模型路径</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 启动session</span></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    sess.run(tf.global_variables_initializer())</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 循环开始训练</span></span><br><span class="line">    <span class="keyword">for</span> epoch <span class="keyword">in</span> <span class="built_in">range</span>(training_epochs):</span><br><span class="line">        avg_cost = <span class="number">0.0</span></span><br><span class="line">        total_batch = <span class="built_in">int</span>(mnist.train.num_examples / batch_size)  <span class="comment"># 计算总批次</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 遍历全数据集</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(total_batch):</span><br><span class="line">            batch_xs, batch_ys = mnist.train.next_batch(batch_size)  <span class="comment"># 读取一个批次样本</span></span><br><span class="line">            params = &#123;x: batch_xs, y: batch_ys&#125;  <span class="comment"># 训练参数</span></span><br><span class="line"></span><br><span class="line">            o, c = sess.run([optimizer, cost], feed_dict=params)  <span class="comment"># 执行训练</span></span><br><span class="line"></span><br><span class="line">            avg_cost += (c / total_batch)  <span class="comment"># 求平均损失值</span></span><br><span class="line"></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;epoch: %d, cost=%.9f&quot;</span> % (epoch + <span class="number">1</span>, avg_cost))</span><br><span class="line"></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;Finished!&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 模型评估</span></span><br><span class="line">    correct_pred = tf.equal(tf.argmax(pred_y, <span class="number">1</span>), tf.argmax(y, <span class="number">1</span>))</span><br><span class="line">    <span class="comment"># 计算准确率</span></span><br><span class="line">    accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;accuracy:&quot;</span>, accuracy.<span class="built_in">eval</span>(&#123;x: mnist.test.images,</span><br><span class="line">                                      y: mnist.test.labels&#125;))</span><br><span class="line">    <span class="comment"># 将模型保存到文件</span></span><br><span class="line">    save_path = saver.save(sess, model_path)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;Model saved:&quot;</span>, save_path)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 测试模型</span></span><br><span class="line"><span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">    sess.run(tf.global_variables_initializer())</span><br><span class="line">    saver.restore(sess, model_path)  <span class="comment"># 加载模型</span></span><br><span class="line"></span><br><span class="line">    batch_xs, batch_ys = mnist.test.next_batch(<span class="number">2</span>)  <span class="comment"># 读取2个测试样本</span></span><br><span class="line">    output = tf.argmax(pred_y, <span class="number">1</span>)  <span class="comment"># 预测结果值</span></span><br><span class="line"></span><br><span class="line">    output_val, predv = sess.run([output, pred_y],  <span class="comment"># 操作</span></span><br><span class="line">                                 feed_dict=&#123;x: batch_xs&#125;)  <span class="comment"># 参数</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;预测结论:\n&quot;</span>, output_val, <span class="string">&quot;\n&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;实际结果:\n&quot;</span>, batch_ys, <span class="string">&quot;\n&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;预测概率:\n&quot;</span>, predv, <span class="string">&quot;\n&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 显示图片</span></span><br><span class="line">    im = batch_xs[<span class="number">0</span>]  <span class="comment"># 第1个测试样本数据</span></span><br><span class="line">    im = im.reshape(<span class="number">28</span>, <span class="number">28</span>)</span><br><span class="line">    pylab.imshow(im)</span><br><span class="line">    pylab.show()</span><br><span class="line"></span><br><span class="line">    im = batch_xs[<span class="number">1</span>]  <span class="comment"># 第2个测试样本数据</span></span><br><span class="line">    im = im.reshape(<span class="number">28</span>, <span class="number">28</span>)</span><br><span class="line">    pylab.imshow(im)</span><br><span class="line">    pylab.show()</span><br></pre></td></tr></table></figure>

<h2 id="利用CNN实现服饰识别"><a href="#利用CNN实现服饰识别" class="headerlink" title="利用CNN实现服饰识别"></a>利用CNN实现服饰识别</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 在fashion_mnist数据集实现服饰识别</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">from</span> tensorflow.contrib.learn.python.learn.datasets.mnist <span class="keyword">import</span> read_data_sets</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">FashionMnist</span>():</span><br><span class="line">    out_featrues1 = <span class="number">12</span>  <span class="comment"># 第一个组卷积池化层输出特征数量(等于第一个卷积层卷积核数量)</span></span><br><span class="line">    out_featrues2 = <span class="number">24</span>  <span class="comment"># 第二个组卷积池化层输出特征数量(等于第二个卷积层卷积核数量)</span></span><br><span class="line">    con_neurons = <span class="number">512</span> <span class="comment"># 全连接层神经元数量</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, path</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        构造方法</span></span><br><span class="line"><span class="string">        :param path:指定数据集路径</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.sess = tf.Session() <span class="comment"># 会话</span></span><br><span class="line">        self.data = read_data_sets(path, one_hot=<span class="literal">True</span>) <span class="comment"># 读取样本文件对象</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">init_weight_variable</span>(<span class="params">self, shape</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        初始化权重方法</span></span><br><span class="line"><span class="string">        :param shape:指定初始化张量的形状</span></span><br><span class="line"><span class="string">        :return:经过初始化后的张量</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        inital = tf.truncated_normal(shape, stddev=<span class="number">0.1</span>) <span class="comment"># 截尾正态分布</span></span><br><span class="line">        <span class="keyword">return</span> tf.Variable(inital)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">init_bias_variable</span>(<span class="params">self, shape</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        初始化偏置</span></span><br><span class="line"><span class="string">        :param shape:指定初始化张量的形状</span></span><br><span class="line"><span class="string">        :return:经过初始化后的张量</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        inital = tf.constant(<span class="number">1.0</span>, shape=shape)</span><br><span class="line">        <span class="keyword">return</span> tf.Variable(inital)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">conv2d</span>(<span class="params">self, x, w</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        二维卷积方法</span></span><br><span class="line"><span class="string">        :param x:原始数据</span></span><br><span class="line"><span class="string">        :param w:卷积核</span></span><br><span class="line"><span class="string">        :return:返回卷积后的结果</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="comment"># input : 输入数据[batch, in_height, in_width, in_channels]</span></span><br><span class="line">        <span class="comment"># filter : 卷积窗口[filter_height, filter_width, in_channels, out_channels]</span></span><br><span class="line">        <span class="comment"># strides: 卷积核每次移动步数，对应着输入的维度方向</span></span><br><span class="line">        <span class="comment"># padding=&#x27;SAME&#x27; ： 输入和输出的张量形状相同</span></span><br><span class="line">        <span class="keyword">return</span> tf.nn.conv2d(x,  <span class="comment"># 原始数据</span></span><br><span class="line">                            w, <span class="comment"># 卷积核</span></span><br><span class="line">                            strides=[<span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>], <span class="comment"># 各个维度上的步长值</span></span><br><span class="line">                            padding=<span class="string">&quot;SAME&quot;</span>) <span class="comment"># 输入和输出矩阵大小相同</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">max_pool_2x2</span>(<span class="params">self, x</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        池化函数</span></span><br><span class="line"><span class="string">        :param x:原始数据</span></span><br><span class="line"><span class="string">        :return:池化后的数据</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> tf.nn.max_pool(x,<span class="comment"># 原始数据</span></span><br><span class="line">                              ksize=[<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">1</span>], <span class="comment"># 池化区域大小</span></span><br><span class="line">                              strides=[<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">1</span>], <span class="comment"># 各个维度上的步长值</span></span><br><span class="line">                              padding=<span class="string">&quot;SAME&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">create_conv_pool_layer</span>(<span class="params">self, <span class="built_in">input</span>, input_features, out_features</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        卷积、激活、池化层</span></span><br><span class="line"><span class="string">        :param input:原始数据</span></span><br><span class="line"><span class="string">        :param input_features:输入特征数量</span></span><br><span class="line"><span class="string">        :param out_features:输出特征数量</span></span><br><span class="line"><span class="string">        :return:卷积、激活、池化层后的数据</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="built_in">filter</span> = self.init_weight_variable([<span class="number">5</span>, <span class="number">5</span>, input_features, out_features])<span class="comment">#卷积核</span></span><br><span class="line">        b_conv = self.init_bias_variable([out_features]) <span class="comment"># 偏置，数量和卷积输出大小一致</span></span><br><span class="line"></span><br><span class="line">        h_conv = tf.nn.relu(self.conv2d(<span class="built_in">input</span>, <span class="built_in">filter</span>) + b_conv)<span class="comment">#卷积，结果做relu激活</span></span><br><span class="line">        h_pool = self.max_pool_2x2(h_conv) <span class="comment">#对激活操作输出做max池化</span></span><br><span class="line">        <span class="keyword">return</span> h_pool</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">create_fc_layer</span>(<span class="params">self, h_pool_flat, input_featrues, con_neurons</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        创建全连接层</span></span><br><span class="line"><span class="string">        :param h_pool_flat:输入数据，经过拉伸后的一维张量</span></span><br><span class="line"><span class="string">        :param input_featrues:输入特征大小</span></span><br><span class="line"><span class="string">        :param con_neurons:神经元数量</span></span><br><span class="line"><span class="string">        :return:全连接</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        w_fc = self.init_weight_variable([input_featrues, con_neurons])<span class="comment">#输出数量等于神经元数量</span></span><br><span class="line">        b_fc = self.init_bias_variable([con_neurons]) <span class="comment">#偏置数量等于输出数量</span></span><br><span class="line">        h_fc1 = tf.nn.relu(tf.matmul(h_pool_flat, w_fc) + b_fc) <span class="comment">#计算wx+b并且做relu激活</span></span><br><span class="line">        <span class="keyword">return</span> h_fc1</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">build</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        组建CNN</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="comment"># 输入数据，N个28*28经过拉伸后的张量</span></span><br><span class="line">        self.x = tf.placeholder(tf.float32, shape=[<span class="literal">None</span>, <span class="number">784</span>])</span><br><span class="line">        x_image = tf.reshape(self.x, [-<span class="number">1</span>, <span class="number">28</span>, <span class="number">28</span>, <span class="number">1</span>]) <span class="comment"># 28*28单通道</span></span><br><span class="line">        self.y_ = tf.placeholder(tf.float32, shape=[<span class="literal">None</span>, <span class="number">10</span>]) <span class="comment"># 标签，对应10个类别</span></span><br><span class="line">        <span class="comment"># 第一组卷积池化层</span></span><br><span class="line">        h_pool1 = self.create_conv_pool_layer(x_image, <span class="number">1</span>, self.out_featrues1)</span><br><span class="line">        <span class="comment"># 第二组卷积池化层</span></span><br><span class="line">        h_pool2 = self.create_conv_pool_layer(h_pool1, <span class="comment"># 上一层输出作为输入</span></span><br><span class="line">                                  self.out_featrues1, <span class="comment"># 上一层输出特征数量作为输入特征数量</span></span><br><span class="line">                                  self.out_featrues2)<span class="comment"># 第二层输出特征数量</span></span><br><span class="line">        <span class="comment"># 全连接层</span></span><br><span class="line">        h_pool2_flat_features = <span class="number">7</span> * <span class="number">7</span> * self.out_featrues2 <span class="comment"># 计算特征点数量</span></span><br><span class="line">        h_pool2_flat = tf.reshape(h_pool2, [-<span class="number">1</span>, h_pool2_flat_features])<span class="comment">#拉升成一维张量</span></span><br><span class="line">        h_fc = self.create_fc_layer(h_pool2_flat, <span class="comment"># 输入</span></span><br><span class="line">                                    h_pool2_flat_features, <span class="comment"># 输入特征数量</span></span><br><span class="line">                                    self.con_neurons) <span class="comment"># 输出特征数量</span></span><br><span class="line">        <span class="comment"># dropout层（通过随机丢弃一部分神经元的更新，防止过拟合）</span></span><br><span class="line">        self.keep_prob = tf.placeholder(<span class="string">&quot;float&quot;</span>) <span class="comment"># 丢弃率</span></span><br><span class="line">        h_fc1_drop = tf.nn.dropout(h_fc, self.keep_prob)</span><br><span class="line">        <span class="comment"># 输出层</span></span><br><span class="line">        w_fc = self.init_weight_variable([self.con_neurons, <span class="number">10</span>])<span class="comment">#512行10列，产生10个输出</span></span><br><span class="line">        b_fc = self.init_bias_variable([<span class="number">10</span>]) <span class="comment"># 10个偏置</span></span><br><span class="line">        y_conv = tf.matmul(h_fc1_drop, w_fc) + b_fc <span class="comment"># 计算wx+b, 预测结果</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 评价</span></span><br><span class="line">        correct_prediction = tf.equal(tf.argmax(y_conv, <span class="number">1</span>),<span class="comment">#取出预测概率中最大的值的索引</span></span><br><span class="line">                                      tf.argmax(self.y_, <span class="number">1</span>))<span class="comment">#取出真实概率中最大的值的索引</span></span><br><span class="line">        <span class="comment"># 将上一步得到的bool类型数组转换为浮点型，并求准确率</span></span><br><span class="line">        self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 损失函数</span></span><br><span class="line">        loss_func = tf.nn.softmax_cross_entropy_with_logits(labels=self.y_,<span class="comment">#真实值</span></span><br><span class="line">                                                            logits=y_conv)<span class="comment">#预测值</span></span><br><span class="line">        cross_entropy = tf.reduce_mean(loss_func)</span><br><span class="line">        <span class="comment"># 优化器</span></span><br><span class="line">        optimizer = tf.train.AdamOptimizer(<span class="number">0.001</span>)</span><br><span class="line">        self.train_step = optimizer.minimize(cross_entropy)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">train</span>(<span class="params">self</span>):</span><br><span class="line">        self.sess.run(tf.global_variables_initializer()) <span class="comment">#初始化</span></span><br><span class="line">        merged = tf.summary.merge_all() <span class="comment">#摘要合并</span></span><br><span class="line"></span><br><span class="line">        batch_size = <span class="number">100</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;beging training...&quot;</span>)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>): <span class="comment"># 迭代训练</span></span><br><span class="line">            total_batch = <span class="built_in">int</span>(self.data.train.num_examples / batch_size)<span class="comment">#计算批次数量</span></span><br><span class="line"></span><br><span class="line">            <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(total_batch):</span><br><span class="line">                batch = self.data.train.next_batch(batch_size)<span class="comment">#获取一个批次样本</span></span><br><span class="line">                params = &#123;self.x: batch[<span class="number">0</span>], self.y_:batch[<span class="number">1</span>],<span class="comment">#输入、标签</span></span><br><span class="line">                          self.keep_prob: <span class="number">0.5</span>&#125; <span class="comment">#丢弃率</span></span><br><span class="line"></span><br><span class="line">                t, acc = self.sess.run([self.train_step, self.accuracy],<span class="comment"># op</span></span><br><span class="line">                                       params) <span class="comment"># 喂入参数</span></span><br><span class="line">                <span class="keyword">if</span> j % <span class="number">100</span> == <span class="number">0</span>:</span><br><span class="line">                    <span class="built_in">print</span>(<span class="string">&quot;epoch: %d, pass: %d, acc: %f&quot;</span>  % (i, j, acc))</span><br><span class="line">    <span class="comment"># 评价</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">eval</span>(<span class="params">self, x, y, keep_prob</span>):</span><br><span class="line">        params = &#123;self.x: x, self.y_: y, self.keep_prob: keep_prob&#125;</span><br><span class="line">        test_acc = self.sess.run(self.accuracy, params)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;Test accuracy %f&#x27;</span> % test_acc)</span><br><span class="line">        <span class="keyword">return</span> test_acc</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 关闭会话</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">close</span>(<span class="params">self</span>):</span><br><span class="line">        self.sess.close()</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    mnist = FashionMnist(<span class="string">&#x27;FASHION_MNIST_data/&#x27;</span>)</span><br><span class="line">    mnist.build()</span><br><span class="line">    mnist.train()</span><br><span class="line"></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;\n----- Test -----&#x27;</span>)</span><br><span class="line">    xs, ys = mnist.data.test.next_batch(<span class="number">100</span>)</span><br><span class="line">    mnist.<span class="built_in">eval</span>(xs, ys, <span class="number">1.0</span>)</span><br><span class="line">    mnist.close()</span><br></pre></td></tr></table></figure>


</article><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E5%AD%A6%E4%B9%A0/">学习</a><a class="post-meta__tags" href="/tags/%E8%AE%B0%E5%BD%95/">记录</a><a class="post-meta__tags" href="/tags/Python/">Python</a><a class="post-meta__tags" href="/tags/%E7%AC%94%E8%AE%B0/">笔记</a><a class="post-meta__tags" href="/tags/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/">深度学习</a></div><div class="post_share"><div class="social-share" data-image="https://image.discover304.top/ai/dl/space_work.jpg?imageView2/2/h/300" data-sites="facebook,twitter,wechat,weibo,qzone,qq,linkedin"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> Donate<div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="/img/wechat.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="/img/alipay.jpg" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/12/01/2021q4/108-3-dl-ex/"><img class="prev-cover" data-lazy-src="https://image.discover304.top/ai/dl/space_work.jpg?imageView2/2/h/300" onerror="onerror=null;src='/img/404.png'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">【深度学习】实例第四部分：PaddlePaddle</div></div></a></div><div class="next-post pull-right"><a href="/2021/12/01/2021q4/108-1-dl-ex/"><img class="next-cover" data-lazy-src="https://image.discover304.top/ai/dl/space_work.jpg?imageView2/2/h/300" onerror="onerror=null;src='/img/404.png'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">【深度学习】实例第二部分：OpenCV</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2021/11/30/2021q4/107-0-dl/" title="【深度学习】概述"><img class="cover" data-lazy-src="https://image.discover304.top/ai/dl/machine-girl.jpg?imageView2/2/h/300" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2021-12-25</div><div class="title">【深度学习】概述</div></div></a></div><div><a href="/2021/11/30/2021q4/107-1-dl-back/" title="【深度学习】基础 叁：反向传播算法"><img class="cover" data-lazy-src="https://image.discover304.top/ai/dl/machine-girl.jpg?imageView2/2/h/300" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2021-12-25</div><div class="title">【深度学习】基础 叁：反向传播算法</div></div></a></div><div><a href="/2021/11/30/2021q4/107-1-dl-loss-gd/" title="【深度学习】基础 贰：损失函数与梯度下降"><img class="cover" data-lazy-src="https://image.discover304.top/ai/dl/machine-girl.jpg?imageView2/2/h/300" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2021-12-25</div><div class="title">【深度学习】基础 贰：损失函数与梯度下降</div></div></a></div><div><a href="/2021/11/30/2021q4/107-1-dl-cnn/" title="【深度学习】基础 肆：卷积神经网络"><img class="cover" data-lazy-src="https://image.discover304.top/ai/dl/machine-girl.jpg?imageView2/2/h/300" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2021-12-25</div><div class="title">【深度学习】基础 肆：卷积神经网络</div></div></a></div><div><a href="/2021/11/30/2021q4/107-1-dl-perceptron/" title="【深度学习】基础 壹：感知机与神经网络"><img class="cover" data-lazy-src="https://image.discover304.top/ai/dl/machine-girl.jpg?imageView2/2/h/300" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2021-12-25</div><div class="title">【深度学习】基础 壹：感知机与神经网络</div></div></a></div><div><a href="/2021/12/02/2021q4/107-4-dl-pdpd-base/" title="【深度学习】框架：PaddlePaddle基础"><img class="cover" data-lazy-src="https://image.discover304.top/ai/dl/02/dog-end-world.jpg?imageView2/2/h/300" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2021-12-25</div><div class="title">【深度学习】框架：PaddlePaddle基础</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> Comment</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside_content" id="aside_content"><div class="card-widget card-info"><div class="card-content"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="/img/head.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">✨YangSier✨</div><div class="author-info__description">Love Everything You Like.</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">243</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">88</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">Categories</div><div class="length-num">23</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://space.bilibili.com/98639326"><i class="fab fa-bilibili"></i><span>Bilibili Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/Discover304" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://blog.csdn.net/Discover304" target="_blank" title="CSDN"><i class="fa-solid fa-c"></i></a><a class="social-icon" href="https://www.zhihu.com/people/discover-56-86-75" target="_blank" title="知乎"><i class="fa-brands fa-zhihu"></i></a><a class="social-icon" href="mailto:hobart.yang@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://jq.qq.com/?_wv=1027&amp;k=EaGddTQg" target="_blank" title="QQ"><i class="fa-brands fa-qq"></i></a></div></div></div><div class="card-widget card-announcement"><div class="card-content"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>Announcement</span></div><div class="announcement_content">✨动态更新：<p style="text-align:center">享受精彩大学生活中。</p>✨聊天划水QQ群：<p style="text-align:center"><a target="_blank" rel="noopener" href="https://jq.qq.com/?_wv=1027&k=EaGddTQg"><strong>兔叽の魔术工房</strong></a><br>942-848-525</p>✨我们的口号是：<p style="text-align:center; color:#39C5BB">人工降神，机械飞升！</p><a target="_blank" rel="noopener" href='https://space.bilibili.com/98639326'><img src='/img/mikulittletrans.png'></a></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="card-content"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9F%A5%E7%9C%8BTensorflow%E7%89%88%E6%9C%AC"><span class="toc-text">查看Tensorflow版本</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Helloworld%E7%A8%8B%E5%BA%8F"><span class="toc-text">Helloworld程序</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%A0%E9%87%8F%E7%9B%B8%E5%8A%A0"><span class="toc-text">张量相加</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9F%A5%E7%9C%8B%E5%9B%BE%E5%AF%B9%E8%B1%A1"><span class="toc-text">查看图对象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8C%87%E5%AE%9A%E6%89%A7%E8%A1%8C%E6%9F%90%E4%B8%AA%E5%9B%BE"><span class="toc-text">指定执行某个图</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9F%A5%E7%9C%8B%E5%BC%A0%E9%87%8F%E5%B1%9E%E6%80%A7"><span class="toc-text">查看张量属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%94%9F%E6%88%90%E5%BC%A0%E9%87%8F"><span class="toc-text">生成张量</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%A0%E9%87%8F%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="toc-text">张量类型转换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%A0%E4%BD%8D%E7%AC%A6%E4%BD%BF%E7%94%A8"><span class="toc-text">占位符使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%94%B9%E5%8F%98%E5%BC%A0%E9%87%8F%E5%BD%A2%E7%8A%B6"><span class="toc-text">改变张量形状</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E5%AD%A6%E8%AE%A1%E7%AE%97"><span class="toc-text">数学计算</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E4%BD%BF%E7%94%A8%E7%A4%BA%E4%BE%8B"><span class="toc-text">变量使用示例</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%AF%E8%A7%86%E5%8C%96"><span class="toc-text">可视化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92"><span class="toc-text">实现线性回归</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E5%9E%8B%E4%BF%9D%E5%AD%98%E4%B8%8E%E5%8A%A0%E8%BD%BD"><span class="toc-text">模型保存与加载</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CSV%E6%A0%B7%E6%9C%AC%E8%AF%BB%E5%8F%96"><span class="toc-text">CSV样本读取</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%BE%E5%83%8F%E6%A0%B7%E6%9C%AC%E8%AF%BB%E5%8F%96"><span class="toc-text">图像样本读取</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0%E6%89%8B%E5%86%99%E4%BD%93%E8%AF%86%E5%88%AB"><span class="toc-text">实现手写体识别</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%A9%E7%94%A8CNN%E5%AE%9E%E7%8E%B0%E6%9C%8D%E9%A5%B0%E8%AF%86%E5%88%AB"><span class="toc-text">利用CNN实现服饰识别</span></a></li></ol></div></div></div><div class="card-widget card-recent-post"><div class="card-content"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/04/24/2023q1/173-nginx-docker-blog-page-depoly/" title="【模板】Hexo Docker Nginx 个人博客服务器部署"><img data-lazy-src="https://image.discover304.top/s16001804242023.png?imageView2/2/h/300" onerror="this.onerror=null;this.src='/img/404.png'" alt="【模板】Hexo Docker Nginx 个人博客服务器部署"/></a><div class="content"><a class="title" href="/2023/04/24/2023q1/173-nginx-docker-blog-page-depoly/" title="【模板】Hexo Docker Nginx 个人博客服务器部署">【模板】Hexo Docker Nginx 个人博客服务器部署</a><time datetime="2023-04-24T06:39:24.000Z" title="Created 2023-04-24 14:39:24">2023-04-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/12/11/2022q4/172-design-idea/" title="【思考】创新点子"><img data-lazy-src="https://image.discover304.top/blog-img/s19313212112022.png" onerror="this.onerror=null;this.src='/img/404.png'" alt="【思考】创新点子"/></a><div class="content"><a class="title" href="/2022/12/11/2022q4/172-design-idea/" title="【思考】创新点子">【思考】创新点子</a><time datetime="2022-12-11T11:08:37.000Z" title="Created 2022-12-11 19:08:37">2022-12-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/12/11/2022q4/171-other-thought/" title="【思考】其他思考"><img data-lazy-src="https://image.discover304.top/blog-img/s19305112112022.png" onerror="this.onerror=null;this.src='/img/404.png'" alt="【思考】其他思考"/></a><div class="content"><a class="title" href="/2022/12/11/2022q4/171-other-thought/" title="【思考】其他思考">【思考】其他思考</a><time datetime="2022-12-11T11:08:17.000Z" title="Created 2022-12-11 19:08:17">2022-12-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/12/11/2022q4/170-key-thought/" title="【思考】核心思考"><img data-lazy-src="https://image.discover304.top/blog-img/s19294112112022.png" onerror="this.onerror=null;this.src='/img/404.png'" alt="【思考】核心思考"/></a><div class="content"><a class="title" href="/2022/12/11/2022q4/170-key-thought/" title="【思考】核心思考">【思考】核心思考</a><time datetime="2022-12-11T11:08:06.000Z" title="Created 2022-12-11 19:08:06">2022-12-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/12/09/2022q4/169-new-r/" title="R: Getting Into Project of R"><img data-lazy-src="https://image.discover304.top/blog-img/s18350812112022.png" onerror="this.onerror=null;this.src='/img/404.png'" alt="R: Getting Into Project of R"/></a><div class="content"><a class="title" href="/2022/12/09/2022q4/169-new-r/" title="R: Getting Into Project of R">R: Getting Into Project of R</a><time datetime="2022-12-09T09:44:06.000Z" title="Created 2022-12-09 17:44:06">2022-12-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/11/28/2022q3/167-2-sp-review/" title="SP Modules Review Contents (3)"><img data-lazy-src="https://image.discover304.top/blog-img/s11220010012022.png?imageView2/2/h/300" onerror="this.onerror=null;this.src='/img/404.png'" alt="SP Modules Review Contents (3)"/></a><div class="content"><a class="title" href="/2022/11/28/2022q3/167-2-sp-review/" title="SP Modules Review Contents (3)">SP Modules Review Contents (3)</a><time datetime="2022-11-28T07:24:39.000Z" title="Created 2022-11-28 15:24:39">2022-11-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/11/17/2022q3/166-10-connected-speech-hidden-markov-model/" title="SP Module 10 Connected Speech &amp; HMM Training"><img data-lazy-src="https://image.discover304.top/blog-img/s11220010012022.png?imageView2/2/h/300" onerror="this.onerror=null;this.src='/img/404.png'" alt="SP Module 10 Connected Speech &amp; HMM Training"/></a><div class="content"><a class="title" href="/2022/11/17/2022q3/166-10-connected-speech-hidden-markov-model/" title="SP Module 10 Connected Speech &amp; HMM Training">SP Module 10 Connected Speech &amp; HMM Training</a><time datetime="2022-11-17T01:47:12.000Z" title="Created 2022-11-17 09:47:12">2022-11-17</time></div></div></div></div></div></div></div></main><footer id="footer" style="background-image: url(https://image.discover304.top/ai/dl/space_work.jpg?imageView2/2/h/300)"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By ✨YangSier✨</div><div><a target="_blank" href="https://beian.miit.gov.cn/" style="display:inline-block;text-decoration:none;height:20px;line-height:20px;"><p style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px; color:#939393;"> 冀ICP备2021025381号-1</p></a></div><div><a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=13060602001430" style="display:inline-block;text-decoration:none;height:20px;line-height:20px;"><img src="/img/beian.png" style="float:left;"/><p style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px; color:#939393;">冀公网安备 13060602001430号</p></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="Switch Between Traditional Chinese And Simplified Chinese">繁</button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="Scroll To Comments"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">Local search</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="Search for Posts" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.spacingElementById('content-inner')
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.spacingElementById('content-inner')
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> {preloader.endLoading()})</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'neutral',
      })
      false && mermaid.init()
    })
  }
}</script><script>function loadValine () {
  function initValine () {
    let initData = {
      el: '#vcomment',
      appId: 'A9RWVELPcIotgfbpp9KLGXQM-gzGzoHsz',
      appKey: 'MLgPQW5h0DPgE8jNkeREKubU',
      placeholder: '欢迎留言呀。（网址是选填，可以留空）',
      avatar: 'monsterid',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-CN',
      recordIP: true,
      serverURLs: 'https://a9rwvelp.lc-cn-n1-shared.com',
      emojiCDN: 'https://cdn.jsdelivr.net/gh/GamerNoTitle/ValineCDN@master/',
      emojiMaps: {"QQ1":"QQ/aini.gif","QQ2":"QQ/aixin.gif","QQ3":"QQ/aoman.gif","QQ4":"QQ/baiyan.gif","QQ5":"QQ/bangbangtang.gif","QQ6":"QQ/baojin.gif","QQ7":"QQ/baoquan.gif","QQ8":"QQ/bishi.gif","QQ9":"QQ/bizui.gif","QQ11":"QQ/cahan.gif","QQ12":"QQ/caidao.gif","QQ13":"QQ/chi.gif","QQ14":"QQ/ciya.gif","QQ15":"QQ/dabing.gif","QQ16":"QQ/daku.gif","QQ17":"QQ/dan.gif","QQ18":"QQ/deyi.gif","QQ19":"QQ/doge.gif","QQ20":"QQ/fadai.gif","QQ21":"QQ/fanu.gif","QQ22":"QQ/fendou.gif","QQ23":"QQ/ganga.gif","QQ24":"QQ/gouyin.gif","QQ25":"QQ/guzhang.gif","QQ26":"QQ/haixiu.gif","QQ27":"QQ/hanxiao.gif","QQ28":"QQ/haobang.gif","QQ29":"QQ/haqian.gif","QQ30":"QQ/hecai.gif","QQ31":"QQ/hexie.gif","QQ32":"QQ/huaixiao.gif","QQ33":"QQ/jie.gif","QQ34":"QQ/jingkong.gif","QQ35":"QQ/jingxi.gif","QQ36":"QQ/jingya.gif","QQ37":"QQ/juhua.gif","QQ38":"QQ/keai.gif","QQ39":"QQ/kelian.gif","QQ40":"QQ/koubi.gif","QQ41":"QQ/ku.gif","QQ42":"QQ/kuaikule.gif","QQ43":"QQ/kulou.gif","QQ44":"QQ/kun.gif","QQ45":"QQ/lanqiu.gif","QQ46":"QQ/leiben.gif","QQ47":"QQ/lenghan.gif","QQ48":"QQ/liuhan.gif","QQ49":"QQ/liulei.gif","QQ50":"QQ/nanguo.gif","QQ51":"QQ/OK.gif","QQ52":"QQ/penxue.gif","QQ53":"QQ/piezui.gif","QQ54":"QQ/pijiu.gif","QQ55":"QQ/qiang.gif","QQ56":"QQ/qiaoda.gif","QQ57":"QQ/qinqin.gif","QQ58":"QQ/qiudale.gif","QQ59":"QQ/quantou.gif","QQ60":"QQ/saorao.gif","QQ61":"QQ/se.gif","QQ62":"QQ/shengli.gif","QQ63":"QQ/shouqiang.gif","QQ64":"QQ/shuai.gif","QQ65":"QQ/shui.gif","QQ66":"QQ/tiaopi.gif","QQ67":"QQ/touxiao.gif","QQ68":"QQ/tu.gif","QQ69":"QQ/tuosai.gif","QQ70":"QQ/weiqu.gif","QQ71":"QQ/weixiao.gif","QQ72":"QQ/woshou.gif","QQ73":"QQ/wozuimei.gif","QQ74":"QQ/wunai.gif","QQ75":"QQ/xia.gif","QQ76":"QQ/xiaojiujie.gif","QQ77":"QQ/xiaoku.gif","QQ78":"QQ/xiaoyanger.gif","QQ79":"QQ/xieyanxiao.gif","QQ80":"QQ/xigua.gif","QQ81":"QQ/xu.gif","QQ82":"QQ/yangtuo.gif","QQ83":"QQ/yinxian.gif","QQ84":"QQ/yiwen.gif","QQ85":"QQ/youhengheng.gif","QQ86":"QQ/youling.gif","QQ87":"QQ/yun.gif","QQ88":"QQ/zaijian.gif","QQ89":"QQ/zhayanjian.gif","QQ90":"QQ/zhemo.gif","QQ91":"QQ/zhouma.gif","QQ92":"QQ/zhuakuang.gif","QQ93":"QQ/zuohengheng.gif","bilibiliHotKey1":"bilibiliHotKey/1.jpg","bilibiliHotKey2":"bilibiliHotKey/10.jpg","bilibiliHotKey3":"bilibiliHotKey/11.jpg","bilibiliHotKey4":"bilibiliHotKey/12.jpg","bilibiliHotKey5":"bilibiliHotKey/13.jpg","bilibiliHotKey6":"bilibiliHotKey/14.jpg","bilibiliHotKey7":"bilibiliHotKey/15.jpg","bilibiliHotKey8":"bilibiliHotKey/16.jpg","bilibiliHotKey9":"bilibiliHotKey/17.jpg","bilibiliHotKey10":"bilibiliHotKey/18.jpg","bilibiliHotKey11":"bilibiliHotKey/19.jpg","bilibiliHotKey12":"bilibiliHotKey/2.jpg","bilibiliHotKey13":"bilibiliHotKey/20.jpg","bilibiliHotKey14":"bilibiliHotKey/21.jpg","bilibiliHotKey15":"bilibiliHotKey/22.jpg","bilibiliHotKey16":"bilibiliHotKey/23.jpg","bilibiliHotKey17":"bilibiliHotKey/24.jpg","bilibiliHotKey18":"bilibiliHotKey/25.jpg","bilibiliHotKey19":"bilibiliHotKey/26.jpg","bilibiliHotKey20":"bilibiliHotKey/27.jpg","bilibiliHotKey21":"bilibiliHotKey/28.jpg","bilibiliHotKey22":"bilibiliHotKey/29.jpg","bilibiliHotKey23":"bilibiliHotKey/3.jpg","bilibiliHotKey24":"bilibiliHotKey/30.jpg","bilibiliHotKey25":"bilibiliHotKey/31.jpg","bilibiliHotKey26":"bilibiliHotKey/32.jpg","bilibiliHotKey27":"bilibiliHotKey/4.jpg","bilibiliHotKey28":"bilibiliHotKey/5.jpg","bilibiliHotKey29":"bilibiliHotKey/6.jpg","bilibiliHotKey30":"bilibiliHotKey/7.jpg","bilibiliHotKey31":"bilibiliHotKey/8.jpg","bilibiliHotKey32":"bilibiliHotKey/9.jpg","Menhera-chan1":"Menhera-chan/1.jpg","Menhera-chan2":"Menhera-chan/10.jpg","Menhera-chan3":"Menhera-chan/100.jpg","Menhera-chan4":"Menhera-chan/101.jpg","Menhera-chan5":"Menhera-chan/102.jpg","Menhera-chan6":"Menhera-chan/103.jpg","Menhera-chan7":"Menhera-chan/104.jpg","Menhera-chan8":"Menhera-chan/105.jpg","Menhera-chan9":"Menhera-chan/106.jpg","Menhera-chan10":"Menhera-chan/107.jpg","Menhera-chan11":"Menhera-chan/108.jpg","Menhera-chan12":"Menhera-chan/109.jpg","Menhera-chan13":"Menhera-chan/11.jpg","Menhera-chan14":"Menhera-chan/110.jpg","Menhera-chan15":"Menhera-chan/111.jpg","Menhera-chan16":"Menhera-chan/112.jpg","Menhera-chan17":"Menhera-chan/113.jpg","Menhera-chan18":"Menhera-chan/114.jpg","Menhera-chan19":"Menhera-chan/115.jpg","Menhera-chan20":"Menhera-chan/116.jpg","Menhera-chan21":"Menhera-chan/117.jpg","Menhera-chan22":"Menhera-chan/118.jpg","Menhera-chan23":"Menhera-chan/119.jpg","Menhera-chan24":"Menhera-chan/12.jpg","Menhera-chan25":"Menhera-chan/120.jpg","Menhera-chan26":"Menhera-chan/13.jpg","Menhera-chan27":"Menhera-chan/14.jpg","Menhera-chan28":"Menhera-chan/15.jpg","Menhera-chan29":"Menhera-chan/16.jpg","Menhera-chan30":"Menhera-chan/17.jpg","Menhera-chan31":"Menhera-chan/18.jpg","Menhera-chan32":"Menhera-chan/19.jpg","Menhera-chan33":"Menhera-chan/2.jpg","Menhera-chan34":"Menhera-chan/20.jpg","Menhera-chan35":"Menhera-chan/21.jpg","Menhera-chan36":"Menhera-chan/22.jpg","Menhera-chan37":"Menhera-chan/23.jpg","Menhera-chan38":"Menhera-chan/24.jpg","Menhera-chan39":"Menhera-chan/25.jpg","Menhera-chan40":"Menhera-chan/26.jpg","Menhera-chan41":"Menhera-chan/27.jpg","Menhera-chan42":"Menhera-chan/28.jpg","Menhera-chan43":"Menhera-chan/29.jpg","Menhera-chan44":"Menhera-chan/3.jpg","Menhera-chan45":"Menhera-chan/30.jpg","Menhera-chan46":"Menhera-chan/31.jpg","Menhera-chan47":"Menhera-chan/32.jpg","Menhera-chan48":"Menhera-chan/33.jpg","Menhera-chan49":"Menhera-chan/34.jpg","Menhera-chan50":"Menhera-chan/35.jpg","Menhera-chan51":"Menhera-chan/36.jpg","Menhera-chan52":"Menhera-chan/37.jpg","Menhera-chan53":"Menhera-chan/38.jpg","Menhera-chan54":"Menhera-chan/39.jpg","Menhera-chan55":"Menhera-chan/4.jpg","Menhera-chan56":"Menhera-chan/40.jpg","Menhera-chan57":"Menhera-chan/41.jpg","Menhera-chan58":"Menhera-chan/42.jpg","Menhera-chan59":"Menhera-chan/43.jpg","Menhera-chan60":"Menhera-chan/44.jpg","Menhera-chan61":"Menhera-chan/45.jpg","Menhera-chan62":"Menhera-chan/46.jpg","Menhera-chan63":"Menhera-chan/47.jpg","Menhera-chan64":"Menhera-chan/48.jpg","Menhera-chan65":"Menhera-chan/49.jpg","Menhera-chan66":"Menhera-chan/5.jpg","Menhera-chan67":"Menhera-chan/50.jpg","Menhera-chan68":"Menhera-chan/51.jpg","Menhera-chan69":"Menhera-chan/52.jpg","Menhera-chan70":"Menhera-chan/53(1).jpg","Menhera-chan71":"Menhera-chan/53.jpg","Menhera-chan72":"Menhera-chan/54.jpg","Menhera-chan73":"Menhera-chan/55.jpg","Menhera-chan74":"Menhera-chan/56.jpg","Menhera-chan75":"Menhera-chan/57.jpg","Menhera-chan76":"Menhera-chan/58.jpg","Menhera-chan77":"Menhera-chan/59.jpg","Menhera-chan78":"Menhera-chan/6.jpg","Menhera-chan79":"Menhera-chan/60.jpg","Menhera-chan80":"Menhera-chan/61.jpg","Menhera-chan81":"Menhera-chan/62.jpg","Menhera-chan82":"Menhera-chan/63.jpg","Menhera-chan83":"Menhera-chan/64.jpg","Menhera-chan84":"Menhera-chan/65.jpg","Menhera-chan85":"Menhera-chan/66.jpg","Menhera-chan86":"Menhera-chan/67.jpg","Menhera-chan87":"Menhera-chan/68.jpg","Menhera-chan88":"Menhera-chan/69.jpg","Menhera-chan89":"Menhera-chan/7.jpg","Menhera-chan90":"Menhera-chan/70.jpg","Menhera-chan91":"Menhera-chan/71.jpg","Menhera-chan92":"Menhera-chan/72.jpg","Menhera-chan93":"Menhera-chan/73.jpg","Menhera-chan94":"Menhera-chan/74.jpg","Menhera-chan95":"Menhera-chan/75.jpg","Menhera-chan96":"Menhera-chan/76.jpg","Menhera-chan97":"Menhera-chan/77.jpg","Menhera-chan98":"Menhera-chan/78.jpg","Menhera-chan99":"Menhera-chan/79.jpg","Menhera-chan100":"Menhera-chan/8.jpg","Menhera-chan101":"Menhera-chan/80.jpg","Menhera-chan102":"Menhera-chan/81.jpg","Menhera-chan103":"Menhera-chan/82.jpg","Menhera-chan104":"Menhera-chan/83.jpg","Menhera-chan105":"Menhera-chan/84.jpg","Menhera-chan106":"Menhera-chan/85.jpg","Menhera-chan107":"Menhera-chan/86.jpg","Menhera-chan108":"Menhera-chan/87.jpg","Menhera-chan109":"Menhera-chan/88.jpg","Menhera-chan110":"Menhera-chan/89.jpg","Menhera-chan111":"Menhera-chan/9.jpg","Menhera-chan112":"Menhera-chan/90.jpg","Menhera-chan113":"Menhera-chan/91.jpg","Menhera-chan114":"Menhera-chan/92.jpg","Menhera-chan115":"Menhera-chan/93.jpg","Menhera-chan116":"Menhera-chan/94.jpg","Menhera-chan117":"Menhera-chan/95.jpg","Menhera-chan118":"Menhera-chan/96.jpg","Menhera-chan119":"Menhera-chan/97.jpg","Menhera-chan120":"Menhera-chan/98.jpg","Menhera-chan121":"Menhera-chan/99.jpg","Sweetie-Bunny1":"Sweetie-Bunny/12311678.png","Sweetie-Bunny2":"Sweetie-Bunny/12311679.png","Sweetie-Bunny3":"Sweetie-Bunny/12311680.png","Sweetie-Bunny4":"Sweetie-Bunny/12311681.png","Sweetie-Bunny5":"Sweetie-Bunny/12311682.png","Sweetie-Bunny6":"Sweetie-Bunny/12311683.png","Sweetie-Bunny7":"Sweetie-Bunny/12311684.png","Sweetie-Bunny8":"Sweetie-Bunny/12311685.png","Sweetie-Bunny9":"Sweetie-Bunny/12311686.png","Sweetie-Bunny10":"Sweetie-Bunny/12311687.png","Sweetie-Bunny11":"Sweetie-Bunny/12311688.png","Sweetie-Bunny12":"Sweetie-Bunny/12311689.png","Sweetie-Bunny13":"Sweetie-Bunny/12311690.png","Sweetie-Bunny14":"Sweetie-Bunny/12311691.png","Sweetie-Bunny15":"Sweetie-Bunny/12311692.png","Sweetie-Bunny16":"Sweetie-Bunny/12311693.png","Sweetie-Bunny17":"Sweetie-Bunny/12311694.png","Sweetie-Bunny18":"Sweetie-Bunny/12311695.png","Sweetie-Bunny19":"Sweetie-Bunny/12311696.png","Sweetie-Bunny20":"Sweetie-Bunny/12311697.png","Sweetie-Bunny21":"Sweetie-Bunny/12311698.png","Sweetie-Bunny22":"Sweetie-Bunny/12311699.png","Sweetie-Bunny23":"Sweetie-Bunny/12311700.png","Sweetie-Bunny24":"Sweetie-Bunny/12311701.png","Sweetie-Bunny25":"Sweetie-Bunny/12311702.png","Sweetie-Bunny26":"Sweetie-Bunny/12311703.png","Sweetie-Bunny27":"Sweetie-Bunny/12311704.png","Sweetie-Bunny28":"Sweetie-Bunny/12311705.png","Sweetie-Bunny29":"Sweetie-Bunny/12311706.png","Sweetie-Bunny30":"Sweetie-Bunny/12311707.png","Sweetie-Bunny31":"Sweetie-Bunny/12311708.png","Sweetie-Bunny32":"Sweetie-Bunny/12311709.png","Sweetie-Bunny33":"Sweetie-Bunny/12311710.png","Sweetie-Bunny34":"Sweetie-Bunny/12311711.png","Sweetie-Bunny35":"Sweetie-Bunny/12311712.png","Sweetie-Bunny36":"Sweetie-Bunny/12311713.png","Sweetie-Bunny37":"Sweetie-Bunny/12311714.png","Sweetie-Bunny38":"Sweetie-Bunny/12311715.png","Sweetie-Bunny39":"Sweetie-Bunny/12311716.png","Sweetie-Bunny40":"Sweetie-Bunny/12311717.png","Majotabi1":"Majotabi/367516718.png","Majotabi2":"Majotabi/367516719.png","Majotabi3":"Majotabi/367516720.png","Majotabi4":"Majotabi/367516721.png","Majotabi5":"Majotabi/367516722.png","Majotabi6":"Majotabi/367516723.png","Majotabi7":"Majotabi/367516724.png","Majotabi8":"Majotabi/367516725.png","Majotabi9":"Majotabi/367516726.png","Majotabi10":"Majotabi/367516727.png","Majotabi11":"Majotabi/367516728.png","Majotabi12":"Majotabi/367516729.png","Majotabi13":"Majotabi/367516730.png","Majotabi14":"Majotabi/367516731.png","Majotabi15":"Majotabi/367516732.png","Majotabi16":"Majotabi/367516733.png","Majotabi17":"Majotabi/367516734.png","Majotabi18":"Majotabi/367516735.png","Majotabi19":"Majotabi/367516736.png","Majotabi20":"Majotabi/367516737.png","Majotabi21":"Majotabi/367516738.png","Majotabi22":"Majotabi/367516739.png","Majotabi23":"Majotabi/367516740.png","Majotabi24":"Majotabi/367516741.png","Majotabi25":"Majotabi/367516742.png","Majotabi26":"Majotabi/367516743.png","Majotabi27":"Majotabi/367516744.png","Majotabi28":"Majotabi/367516745.png","Majotabi29":"Majotabi/367516746.png","Majotabi30":"Majotabi/367516747.png","Majotabi31":"Majotabi/367516748.png","Majotabi32":"Majotabi/367516749.png","Majotabi33":"Majotabi/367516750.png","Majotabi34":"Majotabi/367516751.png","Majotabi35":"Majotabi/367516752.png","Majotabi36":"Majotabi/367516753.png","Majotabi37":"Majotabi/367516754.png","Majotabi38":"Majotabi/367516755.png","Majotabi39":"Majotabi/367516756.png","Majotabi40":"Majotabi/367516757.png","Snow-Miku1":"Snow-Miku/3583066@2x.png","Snow-Miku2":"Snow-Miku/3583067@2x.png","Snow-Miku3":"Snow-Miku/3583068@2x.png","Snow-Miku4":"Snow-Miku/3583069@2x.png","Snow-Miku5":"Snow-Miku/3583070@2x.png","Snow-Miku6":"Snow-Miku/3583071@2x.png","Snow-Miku7":"Snow-Miku/3583072@2x.png","Snow-Miku8":"Snow-Miku/3583073@2x.png","Snow-Miku9":"Snow-Miku/3583074@2x.png","Snow-Miku10":"Snow-Miku/3583075@2x.png","Snow-Miku11":"Snow-Miku/3583076@2x.png","Snow-Miku12":"Snow-Miku/3583077@2x.png","Snow-Miku13":"Snow-Miku/3583078@2x.png","Snow-Miku14":"Snow-Miku/3583079@2x.png","Snow-Miku15":"Snow-Miku/3583080@2x.png","Snow-Miku16":"Snow-Miku/3583081@2x.png","Snow-Miku17":"Snow-Miku/3583082@2x.png","Snow-Miku18":"Snow-Miku/3583083@2x.png","Snow-Miku19":"Snow-Miku/3583084@2x.png","Snow-Miku20":"Snow-Miku/3583085@2x.png","Snow-Miku21":"Snow-Miku/3583086@2x.png","Snow-Miku22":"Snow-Miku/3583087@2x.png","Snow-Miku23":"Snow-Miku/3583088@2x.png","Snow-Miku24":"Snow-Miku/3583089@2x.png","Snow-Miku25":"Snow-Miku/3583090@2x.png","Snow-Miku26":"Snow-Miku/3583091@2x.png","Snow-Miku27":"Snow-Miku/3583092@2x.png","Snow-Miku28":"Snow-Miku/3583093@2x.png","Snow-Miku29":"Snow-Miku/3583094@2x.png","Snow-Miku30":"Snow-Miku/3583095@2x.png","Snow-Miku31":"Snow-Miku/3583096@2x.png","Snow-Miku32":"Snow-Miku/3583097@2x.png","Snow-Miku33":"Snow-Miku/3583098@2x.png","Snow-Miku34":"Snow-Miku/3583099@2x.png","Snow-Miku35":"Snow-Miku/3583100@2x.png","Snow-Miku36":"Snow-Miku/3583101@2x.png","Snow-Miku37":"Snow-Miku/3583102@2x.png","Snow-Miku38":"Snow-Miku/3583103@2x.png","Snow-Miku39":"Snow-Miku/3583104@2x.png","Snow-Miku40":"Snow-Miku/3583105@2x.png"},
      enableQQ: true,
      path: window.location.pathname,
    }

    if (true) { 
      initData.requiredFields= ('nick,mail'.split(','))
    }
    
    if (false) {
      const otherData = false
      initData = Object.assign({}, initData, otherData)
    }
    
    const valine = new Valine(initData)
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.querySelector('#vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script>(function(){
  const bp = document.createElement('script');
  const curProtocol = window.location.protocol.split(':')[0];
  if (curProtocol === 'https') {
    bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
  }
  else{
    bp.src = 'http://push.zhanzhang.baidu.com/push.js';
  }
  bp.dataset.pjax = ''
  const s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(bp, s);
})()</script></div></body></html>